package controllers

import (
	"my-go-project/config"
	"my-go-project/model"
	"my-go-project/utils/token"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

type GlobalList struct {
	Adopt    []AllRound          `json:"Adopt"`
	AllRound []AllRound          `json:"AllRound"`
	User     []model.UserMessage `json:"User"`
}

type UserPageList struct {
	PassageList []AllRound `json:"PassageList"`
}

type AllRound struct {
	AuthorID     int64   `json:"AuthorID"`
	PassageArea  *string `json:"PassageArea,omitempty"`
	PassageID    int64   `json:"PassageID"`
	PassagePic   string  `json:"PassagePic"`
	PassageTitle string  `json:"PassageTitle"`
	PassageType  string  `json:"PassageType"`
	ProfilePhoto string  `json:"ProfilePhoto"`
	UName        string  `json:"UName"`
	IfLiked      bool    `json:"IfLiked"`
}

func GlobalSearch(ctx *gin.Context) {
	searchMessage := ctx.Param("SearchMessage")
	var globalList GlobalList
	globalPassageList := []AllRound{}
	adoptPassageList := []AllRound{}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	if len(searchMessage) == 0 {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": "搜索信息不能为空",
		})
	}

	global, adopt, err := model.SearchGlobalList(searchMessage)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	for _, g := range global {
		userMessage, err := model.GetUserMessage(int(g.AuthorID))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		ifLiked, err := model.IfLiked(int(g.PassageID), int(uid))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		passage := AllRound{
			ProfilePhoto: userMessage.ProfilePhoto,
			UName:        userMessage.UName,
			AuthorID:     g.AuthorID,
			PassageArea:  g.PassageArea,
			PassageID:    g.PassageID,
			PassagePic:   g.PassagePic,
			PassageType:  g.PassageType,
			PassageTitle: g.PassageTitle,
			IfLiked:      ifLiked,
		}
		globalPassageList = append(globalPassageList, passage)
	}
	for i := range globalPassageList {
		p := &globalPassageList[i] // 通过指针引用修改原始元素
		fileName := "0"
		files, err := os.ReadDir(config.AppConfig.File.AbsolutePath + p.PassagePic)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		for _, file := range files {
			extName := path.Ext(file.Name())
			res := strings.Replace(file.Name(), extName, "", -1)
			if res == fileName {
				p.PassagePic += file.Name()
				break
			}
		}
		if p.PassageArea != nil {
			pos := strings.Index(*p.PassageArea, " ")
			tmp := (*p.PassageArea)[0:pos]
			p.PassageArea = &tmp
		}
	}

	for _, a := range adopt {
		userMessage, err := model.GetUserMessage(int(a.AuthorID))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		ifLiked, err := model.IfLiked(int(a.PassageID), int(uid))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		passage := AllRound{
			ProfilePhoto: userMessage.ProfilePhoto,
			UName:        userMessage.UName,
			AuthorID:     a.AuthorID,
			PassageArea:  a.PassageArea,
			PassageID:    a.PassageID,
			PassagePic:   a.PassagePic,
			PassageType:  a.PassageType,
			PassageTitle: a.PassageTitle,
			IfLiked:      ifLiked,
		}
		adoptPassageList = append(adoptPassageList, passage)
	}
	for i := range adoptPassageList {
		p := &adoptPassageList[i] // 通过指针引用修改原始元素
		fileName := "0"
		files, err := os.ReadDir(config.AppConfig.File.AbsolutePath + p.PassagePic)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		for _, file := range files {
			extName := path.Ext(file.Name())
			res := strings.Replace(file.Name(), extName, "", -1)
			if res == fileName {
				p.PassagePic += file.Name()
				break
			}
		}
		if p.PassageArea != nil {
			pos := strings.Index(*p.PassageArea, " ")
			tmp := (*p.PassageArea)[0:pos]
			p.PassageArea = &tmp
		}
	}

	userMessage, err := model.SearchUserMessage(searchMessage)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	globalList.AllRound = globalPassageList
	globalList.Adopt = adoptPassageList
	globalList.User = userMessage
	ctx.JSON(http.StatusOK, globalList)
}

func UserSearch(ctx *gin.Context) {
	var userListResponse UserPageList
	var userPageList []AllRound
	searchMessage := ctx.Param("SearchMessage")
	userID, err := strconv.Atoi(ctx.Param("UserID"))
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	userList, err := model.SearchUserList(searchMessage, userID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	for _, u := range userList {
		userMessage, err := model.GetUserMessage(int(u.AuthorID))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		ifLiked, err := model.IfLiked(int(u.PassageID), int(uid))
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		passage := AllRound{
			ProfilePhoto: userMessage.ProfilePhoto,
			UName:        userMessage.UName,
			AuthorID:     u.AuthorID,
			PassageArea:  u.PassageArea,
			PassageID:    u.PassageID,
			PassagePic:   u.PassagePic,
			PassageType:  u.PassageType,
			PassageTitle: u.PassageTitle,
			IfLiked:      ifLiked,
		}
		userPageList = append(userPageList, passage)
	}
	for i := range userPageList {
		p := &userPageList[i] // 通过指针引用修改原始元素
		fileName := "0"
		files, err := os.ReadDir(config.AppConfig.File.AbsolutePath + p.PassagePic)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		for _, file := range files {
			extName := path.Ext(file.Name())
			res := strings.Replace(file.Name(), extName, "", -1)
			if res == fileName {
				p.PassagePic += file.Name()
				break
			}
		}
		if p.PassageArea != nil {
			pos := strings.Index(*p.PassageArea, " ")
			tmp := (*p.PassageArea)[0:pos]
			p.PassageArea = &tmp
		}
	}
	userListResponse.PassageList = userPageList
	ctx.JSON(http.StatusOK, userListResponse)
}
